package com.example.xiaomiao.Util;

import com.example.xiaomiao.DO.Picture;
import com.example.xiaomiao.Mapper.PictureMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.example.xiaomiao.Util.MyConstants.PICTURE_ADDRESS;
import static com.example.xiaomiao.Util.MyConstants.PICTURE_KEY;

@Component
public class ScheduledUtil {
    @Resource
    PictureMapper pictureMapper;
    @Resource
    CacheDataBaseUtil cacheDataBaseUtil;
    private static final Logger logger = LoggerFactory.getLogger(ScheduledUtil.class);

    @Scheduled(cron = "0 30 4 */7 * ?")
    @Transactional(rollbackFor = Exception.class)
    public void cleanUnusedPicture(){
        List<Picture> wild_pictures = pictureMapper.getWildPicture();
        List<String> md5s = new ArrayList<>();
        List<String> paths = new ArrayList<>();
        for(Picture wild_picture : wild_pictures) {
            md5s.add(wild_picture.getMd5());
            paths.add(PICTURE_ADDRESS + "/" + wild_picture.getPicture_id() + ".jpg");
        }
        try {
            if(!md5s.isEmpty()) {
                cacheDataBaseUtil.deleteManyById(PICTURE_KEY, md5s, md5s2 -> pictureMapper.deleteByMD5s(md5s2));
                for (String path : paths) {
                    File file = new File(path);
                    if (file.exists())
                        file.delete();
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
